package com.ngmaster.apiserver.services.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ngmaster.apiserver.common.LocationBody;
import com.ngmaster.apiserver.config.BaiduConfig;
import com.ngmaster.apiserver.services.ILocationService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class LocationService implements ILocationService {

	@Autowired
	private BaiduConfig baiduConfig = new BaiduConfig();

	private OkHttpClient okHttpClient = new OkHttpClient();

	private static LocationBody locationBodySingle = new LocationBody();

	@Override
	public LocationBody getCityByLongitudeAndLatitude(String location) throws IOException {
		String uri = baiduConfig.getUri();
		String api = baiduConfig.getApi();
		String ak = baiduConfig.getAk();
		StringBuilder getUrl = new StringBuilder();
		getUrl.append(uri).append(api).append("?");
		getUrl.append("location=").append(location);
		getUrl.append("&extensions_town=true&output=json&pois=1");
		getUrl.append("&ak=").append(ak);
		Request request = new Request.Builder().url(getUrl.toString()).build();
		Response response = okHttpClient.newCall(request).execute();
		if (!response.isSuccessful()) {
			throw new IOException("getCityByLongitudeAndLatitude Unexpected code " + response);
		}
		String body = response.body().string();
		JSONObject jsonObject = JSON.parseObject(body);
		LocationBody locationBody = locationBodySingle;
		if (jsonObject != null) {
			locationBody = new LocationBody();
			StringBuilder locationStr = new StringBuilder();
			JSONObject result = jsonObject.getJSONObject("result");
			if (baiduConfig.isDetailAddress()) {
				String formattedAddress = result.getString("formatted_address");
				locationStr.append(formattedAddress);

			} else {
				JSONObject addressComponent = result.getJSONObject("addressComponent");
				String country = addressComponent.getString("country");
				String province = addressComponent.getString("province");
				String city = addressComponent.getString("city");
				String district = addressComponent.getString("district");
				if (baiduConfig.isContainsCountry()) {
					locationStr.append(country);
				}
				if (province.equalsIgnoreCase(city)) {
					locationStr.append(city);
				} else {
					locationStr.append(province);
					locationStr.append(city);
				}
				locationStr.append(district);
			}
			locationBody.setLocation(locationStr.toString());

		}
		return locationBody;
	}
}
